#R version 4.4.3 (2025-02-28 ucrt)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 11 x64 

library(dplyr) #1.1.4
library(ggplot2) #3.5.1
library(readr) #2.1.5
library(haven) #2.5.4
library(estimatr) #1.0.6
library(broom.mixed) #0.2.9.6
library(lme4) #1.1-37
library(countrycode) #1.6.1
library(forcats) #1.0.0

`%notin%` <- function(x,y) !(x %in% y) 

setwd("C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/cps/replication")

#pooled estimates
mp <- read_dta("data/stata/model1.1.dta") |>
  mutate(Sample = "Pooled") |>
  filter(var %in% c("pi1", "prior_pi", "asp_dummy"))

#at t=0
m0 <- read_dta("data/stata/model1.2.dta") |>
  mutate(Sample = "None") |>
  filter(var %in% c("pi1", "prior_pi", "asp_dummy"))

#at t=first election
m1 <- read_dta("data/stata/model1.3.dta") |>
  mutate(Sample = "First") |>
  filter(var %in% c("pi1", "prior_pi", "asp_dummy"))

#at t=second election
m2 <- read_dta("data/stata/model1.4.dta") |>
  mutate(Sample = "Second") |>
  filter(var %in% c("pi1", "prior_pi", "asp_dummy"))

#at t=third election and beyond
m3 <- read_dta("data/stata/model1.5.dta") |>
  mutate(Sample = "Third-plus") |>
  filter(var %in% c("pi1", "prior_pi", "asp_dummy"))

#fig1 left hand side
rbind(m0, m1, m2, m3, mp) |>
  mutate(Sample = factor(Sample, levels = c("None", "First", "Second", "Third-plus", "Pooled"))) |>
  mutate(var = recode(var, "pi1" = "Incumbent PI", "prior_pi" = "Prior PI", "asp_dummy" = "ASP")) |>
  filter(var %in% c("Incumbent PI", "Prior PI", "ASP")) |>
  mutate(conf.low = coef - 1.96*stderr, conf.high = coef + 1.96*stderr) |> 
  ggplot(aes(x = Sample, y = coef, ymin = conf.low, ymax = conf.high, color = var, shape = var)) +
  geom_pointrange(position = position_jitterdodge(dodge.width = 0.75, jitter.width = 0.2), size = 0.5) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_line(aes(y = coef - 100), linetype = "solid", color = NA) +  # Setting color to NA to remove legend
  geom_point(aes(y = coef - 100), shape = NA, color = NA) +  # Setting color and shape to NA to remove legend
  theme_bw() +
  xlab("Elections Since Democratization") +
  ylab("Party Institutionalization") +
  ylim(-0.55, 0.55) +
  scale_color_grey(name = "Variable", start = 0, end = 0.8) +
  scale_shape_manual("Variable", values = c(15, 16, 17)) + 
  theme(legend.position = "bottom")  +
  ggtitle("OLS - Panel Corrected Standard Errors") +
  theme(plot.title = element_text(hjust = 0.5))

#ggsave(filename = "C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/plots/fig1_1.jpg", dpi = 500, width = 5, height = 5)

#Random Effects model#####
#read in data using GWF
gwf <- read_csv("data/gwf_panel.csv") %>% 
  select(countryname, year, v2xps_party, v2x_polyarchy, gwf_duration, gwf_regime, gwf_prior, prior_pi, pi1, pi2, pi3, pi4, asp_dummy, ruling, lgdp, gwf_pduration, gwf_number, fsu, ussr_sat, regime_elecs, av_dm) %>% 
  mutate(ccode = countrycode(countryname, origin = "country.name", destination = "cown")) |> 
  mutate_at(vars(pi1, pi2, pi3, pi4), ~ifelse(gwf_prior %in% c("Personal", "Military", "Party", "Monarchy") & is.nan(.) | gwf_prior %in% c("Personal", "Military", "Party", "Monarchy") & is.na(.), 0, .)) %>% 
  filter(gwf_prior %in% c("Party", "Military", "Personal") & gwf_regime == "democracy") %>% 
  mutate(asp_dummy = ifelse(is.na(asp_dummy), 0, asp_dummy)) %>% 
  mutate(gwf_prior = factor(gwf_prior, levels = c("Party", "Personal", "Military"))) %>% 
  mutate(elections = ifelse(regime_elecs >= 3, "Third-plus", regime_elecs),  elections = recode(elections, `0` = "None", `1` = "First", `2` = "Second"), 
         elections = factor(elections, levels = c("None", "First", "Second", "Third-plus"))) 

#select relevant variables and exclude NA
gwf8 <- gwf |> select(v2xps_party, gwf_prior, pi1, prior_pi, asp_dummy, v2x_polyarchy, lgdp, gwf_pduration, gwf_number, fsu, ussr_sat, regime_elecs, av_dm, elections, ccode) |> na.omit()

m1 <- lmer(v2xps_party ~ gwf_prior + pi1*elections + prior_pi + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m2 <- lmer(v2xps_party ~ gwf_prior + pi1*relevel(elections, ref = "First") + prior_pi + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m3 <- lmer(v2xps_party ~ gwf_prior + pi1*relevel(elections, ref = "Second") + prior_pi + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m4 <- lmer(v2xps_party ~ gwf_prior + pi1*relevel(elections, ref = "Third-plus") + prior_pi + asp_dummy + + av_dm + (1 | ccode), data = gwf8, REML=FALSE)

#extract pi1 coefficient for each round of elections
tm1 <- tidy(m1, conf.int = TRUE) |> filter(term == "pi1") |> mutate(Sample = "None")
tm2 <- tidy(m2, conf.int = TRUE) |> filter(term == "pi1") |> mutate(Sample = "First")
tm3 <- tidy(m3, conf.int = TRUE) |> filter(term == "pi1") |> mutate(Sample = "Second")
tm4 <- tidy(m4, conf.int = TRUE) |> filter(term == "pi1") |> mutate(Sample = "Third-plus")

#rerun models interacting prior_pi instead
m5 <- lmer(v2xps_party ~ gwf_prior + prior_pi*elections + pi1 + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m6 <- lmer(v2xps_party ~ gwf_prior + prior_pi*relevel(elections, ref = "First") + pi1 + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m7 <- lmer(v2xps_party ~ gwf_prior + prior_pi*relevel(elections, ref = "Second") + pi1 + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)
m8 <- lmer(v2xps_party ~ gwf_prior + prior_pi*relevel(elections, ref = "Third-plus") + pi1 + asp_dummy + (1 | ccode), data = gwf8, REML=FALSE)

#extract prior_pi coefficient for each round of elections
tm5 <- tidy(m5, conf.int = TRUE) |> filter(term == "prior_pi") |> mutate(Sample = "None")
tm6 <- tidy(m6, conf.int = TRUE) |> filter(term == "prior_pi") |> mutate(Sample = "First")
tm7 <- tidy(m7, conf.int = TRUE) |> filter(term == "prior_pi") |> mutate(Sample = "Second")
tm8 <- tidy(m8, conf.int = TRUE) |> filter(term == "prior_pi") |> mutate(Sample = "Third-plus")

#rerun models interacting asp
m9 <- lmer(v2xps_party ~ gwf_prior + asp_dummy*elections + pi1 + prior_pi + (1 | ccode), data = gwf8, REML=FALSE)
m10 <- lmer(v2xps_party ~ gwf_prior + asp_dummy*relevel(elections, ref = "First") + pi1 + prior_pi + (1 | ccode), data = gwf8, REML=FALSE)
m11 <- lmer(v2xps_party ~ gwf_prior + asp_dummy*relevel(elections, ref = "Second") + pi1 + prior_pi + (1 | ccode), data = gwf8, REML=FALSE)
m12 <- lmer(v2xps_party ~ gwf_prior + asp_dummy*relevel(elections, ref = "Third-plus") + pi1 + prior_pi + (1 | ccode), data = gwf8, REML=FALSE)

#extract asp coefficient for each round of elections
tm9 <- tidy(m9, conf.int = TRUE) |> filter(term == "asp_dummy") |> mutate(Sample = "None")
tm10 <- tidy(m10, conf.int = TRUE) |> filter(term == "asp_dummy") |> mutate(Sample = "First")
tm11 <- tidy(m11, conf.int = TRUE) |> filter(term == "asp_dummy") |> mutate(Sample = "Second")
tm12 <- tidy(m12, conf.int = TRUE) |> filter(term == "asp_dummy") |> mutate(Sample = "Third-plus")

rbind(tm1, tm2, tm3, tm4, tm5, tm6, tm7, tm8, tm9, tm10, tm11, tm12) |> 
  mutate(term = case_when(term == "pi1" ~ "Incumbent PI", term == "prior_pi" ~ "Prior PI", term == "asp_dummy" ~ "ASP"),
         Sample = fct_relevel(Sample, c("None", "First", "Second", "Third-plus"))) |> 
  ggplot(aes(x = Sample, y = estimate, ymin = conf.low, ymax = conf.high, color = term, shape = term)) +
  geom_pointrange(position = position_jitterdodge(dodge.width = 0.75, jitter.width = 0.2), size = 0.5) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_line(aes(y = estimate - 100), linetype = "solid", color = NA) +  # Setting color to NA to remove legend
  geom_point(aes(y = estimate - 100), shape = NA, color = NA) +  # Setting color and shape to NA to remove legend
  theme_bw() +
  xlab("Elections Since Democratization") +
  ylab("Party Institutionalization") +
  ylim(-0.55, 0.55) +
  scale_color_grey(name = "Variable", start = 0, end = 0.8) +
  scale_shape_manual("Variable", values = c(15, 16, 17)) + 
  theme(legend.position = "bottom")  +
  ggtitle("Random Effects Models") +
  theme(plot.title = element_text(hjust = 0.5))

#save to file
#ggsave(filename = "C:/Users/selfd/Documents/autopartyinstitutionalization/legacy/plots/fig1_2.jpg", dpi = 500, width = 5, height = 5)